import "./index.scss";
import { useEffect, useState } from "react";
import {
  SearchOutlined,
  DoubleLeftOutlined,
  CloseOutlined,
} from "@ant-design/icons";
import {
  Divider,
  Button,
  Table,
  Form,
  Input,
  Drawer,
  Select,
  Modal,
  Breadcrumb,
  DatePicker,
  message,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import type { DrawerProps, RadioChangeEvent } from "antd";
import axios from "../../../utils/http";
import timeTrans from "../../../components/timeTrans";
import "dayjs/locale/zh-cn";
import locale from "antd/es/date-picker/locale/zh_CN";

interface a {
  userId: number;
}
interface DataType {
  key: React.Key;
  projectNames: string;
  noticeContent: string;
  endTime: string;
  notifyInitiator: string;
  status: number;
}

const NoticePayment: React.FC = () => {
  //渲染数据
  const getUser = () => {
    axios({
      url: "/noticepayget",
      params: {
        search: "",
      },
    }).then((res: { [propName: string]: any }) => {
      console.log(res, "noticePay");
      if (res.error == 0) {
        // console.log(res.data);
        let _data = res.data.map((v: { key_n: number }) => {
          return { ...v, key: v.key_n };
        });
        setData(_data);
      }
    });
  };
  useEffect(() => {
    getUser();
  }, []);

  //新增
  const [placementAdd] = useState<DrawerProps["placement"]>("top");
  const [addOpen, setAddOpen] = useState(false);
  const config = {
    rules: [
      {
        type: "object" as const,
        required: true,
        message: "请选择通知截至时间",
      },
    ],
  };
  const onAdd = (data: { [propName: string]: any }) => {
    data.endTime = data.endTime.format("YYYY-MM-DD");
    // console.log(data);
    axios({
      url: "/noticePayAdd",
      method: "post",
      data: {
        projectNames: data.projectNames,
        noticeContent: data.noticeContent,
        endTime: data.endTime,
        notifyInitiator: data.notifyInitiator,
        status_n: "0",
      },
    }).then((res: { [propName: string]: any }) => {
      if (res.error == 0) {
        message.success("添加成功");
        getUser();
      }
    });
    setAddOpen(false);
  };
  //新增完

  //删除
  const [selData, setSelData] = useState([]);
  const [DeltOpen, setDelOpen] = useState(false);
  const delNotice = () => {
    if (selData.length > 0 && selData != null) {
      setDelOpen(true);
    } else {
      message.error("请选择要删除的角色");
    }
  };
  //删除里的确定
  const ensureDel = () => {
    let key: any;
    selData.map((v: { [propName: string]: any }) => {
      key = v.key_n;
    });
    // console.log(key, "ppp");
    axios({
      url: "/noticePaydel",
      method: "post",
      data: {
        key: key,
      },
    }).then((res: { [propName: string]: any }) => {
      if (res.error == 0) {
        getUser();
      }
    });
    setDelOpen(false);
  };
  //删除完

  //发起通知
  //业务逻辑：先判断是否选择那条通知，然后再判断是否过通知截至日期，
  //如果过了提示过了日期，询问是否修改通知截至日期并重新发布（修改截至时间和状态）
  //如果没过 直接发布（修改状态）
  const [openNotice, setOpenNotice] = useState(false);
  const InitiateNotice = () => {
    if (selData.length > 0 && selData != null) {
      setOpenNotice(true);
    } else {
      message.error("请选择要发起的通知");
    }
  };
  const [key, setKey] = useState<any>();
  const [openInquire, setOpenInquire] = useState(false);
  const ensureOpenNotice = () => {
    let status: any;
    let _endTime: any;
    selData.map((v: { [propName: string]: any }) => {
      setKey(v.key_n);
      status = v.status_n;
      _endTime = v.endTime;
    });
    let time = timeTrans(_endTime, 0);
    let nowTime = timeTrans(Date.now(), 0);
    // console.log(time, nowTime, "ddddd");

    if (status == 0) {
      if (time < nowTime) {
        // 弹出询问提示框
        setOpenInquire(true);
      } else {
        axios({
          url: "/noticePayEdit",
          method: "post",
          data: {
            key_n: key,
            status_n: "1",
          },
        }).then((res: { [propName: string]: any }) => {
          if (res.error == 0) {
            getUser();
            message.success("通知已发布");
          }
        });
      }
    } else {
      message.error("此通知已发布！");
    }
    setOpenNotice(false);
  };

  //询问是否再次发起通知的确定
  const [openEditTime, setOpenEditTime] = useState(false);
  const [editTimeForm] = Form.useForm();
  //修改时间后再发起通知的确定
  const ensureOpenEditTime = () => {
    let _editTime = editTimeForm.getFieldsValue();
    axios({
      url: "/noticePayEditTime",
      method: "post",
      data: {
        key_n: key,
        endTime: timeTrans(_editTime.endTime.$d, 0),
        status_n: "1",
      },
    }).then((res: { [propName: string]: any }) => {
      if(res.error==0){
        getUser();
        message.success("通知已发布");
        setOpenEditTime(false)
        setOpenInquire(false)
        setOpenNotice(false)
      }
    });
  };
  //发起通知完

  //搜索
  const [searchForm] = Form.useForm();
  const searchNotice = (search: any) => {
    if (search.projectNames.trim() == "") {
      getUser();
    } else {
      let _data = data.filter((v: { projectNames: string }) => {
        return v.projectNames.includes(search.projectNames);
      });
      setData(_data);
    }
  };

  //重置
  const reset = () => {
    searchForm.setFieldsValue({ projectNames: "" });
    getUser();
  };

  //高级筛选
  const [open, setOpen] = useState(false);
  const [placement, setPlacement] = useState<DrawerProps["placement"]>("top");
  const senior = () => {
    if (open == false) {
      setOpen(true);
    } else {
      setOpen(false);
    }
  };
  const advancedFilter = (search: any) => {
    // console.log(search);
    let _endTime;
    if (search.endTime) {
      _endTime = timeTrans(search.endTime.$d, 0);
    } else {
      //当没选时间时，设置一个超级大的时间值
      let time1 = "2053-12-12 16:28:37";
      _endTime = timeTrans(time1, 0);
    }

    axios({
      url: "/noticePayFilter",
      method: "post",
      data: {
        projectNames: search.projectNames || "",
        endTime: _endTime,
        status_n: search.status || "",
      },
    }).then((res: { [propName: string]: any }) => {
      if (res.error == 0) {
        let _data = res.data.map((v: { key_n: number }) => {
          return { ...v, key: v.key_n };
        });
        setData(_data);
        setOpen(false);
      }
    });
  };
  // 表格数据
  const columns: ColumnsType<DataType> = [
    {
      title: "通知标题",
      dataIndex: "projectNames",
    },
    {
      title: "通知内容",
      dataIndex: "noticeContent",
    },
    {
      title: "通知截至时间",
      dataIndex: "endTime",
      render: (text) => <span>{timeTrans(text, 0)}</span>,
    },
    {
      title: "通知发起人",
      dataIndex: "notifyInitiator",
    },

    {
      title: "状态",
      dataIndex: "status_n",
      render: (text: number) => <span> {text == 0 ? "未通知" : "已通知"}</span>,
    },
  ];
  const [data, setData] = useState([]);

  //分页
  const pagination = {
    defaultPageSize: 5,
    defaultCurrent: 1,
    total: data.length,
    showQuickJumper: true,
    showSizeChanger: true,
    pageSizeOptions: [5, 10, 15, 20],
  };
  //当前数据
  const [nowData, setNowData] = useState({});
  //表格的单选
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: any) => {
      // console.log(`selectedRowKeys`, selectedRows);
      setSelData(selectedRows);
    },
  };

  

  return (
    <div className="balance">
      {/* 路径 */}
      <div className="title">
        <Breadcrumb separator=">">
          <Breadcrumb.Item>缴费通知管理</Breadcrumb.Item>
          <Breadcrumb.Item href="#">缴费通知管理</Breadcrumb.Item>
        </Breadcrumb>
      </div>
      <Divider />
      <div>
        <Form
          className="search"
          layout="inline"
          onFinish={searchNotice}
          form={searchForm}
        >
          <Form.Item>
            <Button
              type="primary"
              style={{ background: "#69657e" }}
              onClick={() => {
                setAddOpen(true);
              }}
            >
              新增
            </Button>
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              style={{ background: "#69657e" }}
              onClick={delNotice}
            >
              删除
            </Button>
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              style={{ background: "#69657e" }}
              onClick={InitiateNotice}
            >
              发起通知
            </Button>
          </Form.Item>
          <Form.Item name="projectNames">
            <Input placeholder="请输入通知标题" />
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              style={{ background: "#69657e" }}
              icon={<SearchOutlined />}
              htmlType="submit"
            >
              搜索
            </Button>
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              style={{ background: "#69657e" }}
              onClick={reset}
            >
              重置
            </Button>
          </Form.Item>
          <Divider type="vertical" className="ver" />
          <Form.Item>
            <Button type="link" style={{ color: "#52a6ff" }} onClick={senior}>
              高级筛选
              <DoubleLeftOutlined rotate={270} style={{ color: "#d6d6d6" }} />
            </Button>
          </Form.Item>
        </Form>
      </div>
      {/* 高级筛选弹框 */}
      <div className="site-drawer-render-in-current-wrapper">
        <Drawer
          placement={placement}
          closable={false}
          onClose={() => {
            setOpen(false);
          }}
          open={open}
          key={placement}
          getContainer={false}
          height={150}
        >
          <Form className="senior" layout="inline" onFinish={advancedFilter}>
            <Form.Item label="通知标题" name="projectNames">
              <Input placeholder="请输入通知标题" />
            </Form.Item>
            <Form.Item name="endTime" label="通知截至时间">
              <DatePicker
                showTime
                format="YYYY-MM-DD HH:mm:ss"
                locale={locale}
              />
            </Form.Item>
            <Form.Item label="状态" name="status">
              <Select style={{ width: 180 }} placeholder="请选择状态">
                <Select.Option value="0">未通知</Select.Option>
                <Select.Option value="1">已通知</Select.Option>
              </Select>
            </Form.Item>
            <div
              className="seniorClose"
              onClick={() => {
                setOpen(false);
              }}
            >
              <CloseOutlined />
            </div>
            <div className="seniorBtn">
              <Form.Item>
                <Button
                  type="primary"
                  style={{ background: "#69657e" }}
                  htmlType="submit"
                >
                  查询
                </Button>
              </Form.Item>
              <Form.Item>
                <Button type="primary" style={{ background: "#69657e" }}>
                  重置
                </Button>
              </Form.Item>
            </div>
          </Form>
        </Drawer>
      </div>

      {/* 表格 */}
      <Table
        rowSelection={{
          type: "radio",
          ...rowSelection,
        }}
        bordered={true}
        columns={columns}
        dataSource={data}
        pagination={pagination}
      />

      {/* 新增 */}
      <div className="add">
        <Drawer
          title="缴费通知管理   新增"
          placement={placementAdd}
          closable={false}
          onClose={() => {
            setAddOpen(false);
          }}
          destroyOnClose={true}
          open={addOpen}
          key={placement}
          contentWrapperStyle={{
            position: "absolute",
            top: "25%",
            left: "20%",
            width: "70%",
          }}
        >
          <Form
            layout="inline"
            onFinish={onAdd}
            style={{ position: "relative", justifyContent: "center" }}
          >
            <Form.Item
              label="通知标题"
              name="projectNames"
              rules={[{ required: true }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="通知发起人"
              name="notifyInitiator"
              style={{ margin: "0 10px 8px 8px" }}
              rules={[
                {
                  required: true,
                  message: "必须添加姓名",
                },
              ]}
            >
              <Input />
            </Form.Item>
            <Form.Item name="endTime" label="通知截至时间" {...config}>
              <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" />
            </Form.Item>
            <Form.Item
              label="通知内容"
              name="noticeContent"
              style={{ marginLeft: "10px" }}
            >
              <Input.TextArea rows={5} cols={119} />
            </Form.Item>
            <div
              className="addClose"
              onClick={() => {
                setOpen(false);
              }}
            ></div>
            <div className="addBtn">
              <Form.Item>
                <Button
                  type="primary"
                  style={{
                    background: "#69657e",
                    position: "absolute",
                    top: "160px",
                    left: "-500px",
                  }}
                  onClick={() => {
                    setAddOpen(false);
                  }}
                >
                  取消
                </Button>
                <Button
                  type="primary"
                  style={{
                    background: "#69657e",
                    position: "absolute",
                    top: "160px",
                    left: "-420px",
                  }}
                  htmlType="submit"
                >
                  保存
                </Button>
              </Form.Item>
            </div>
          </Form>
        </Drawer>
      </div>

      {/* 删除弹窗 */}
      <Modal
        title="提示"
        centered
        open={DeltOpen}
        onOk={ensureDel}
        onCancel={() => setDelOpen(false)}
      >
        <p>确定要删除该用户的角色？</p>
      </Modal>

      {/* 发起通知弹窗 */}
      <Modal
        title="提示"
        centered
        open={openNotice}
        onOk={ensureOpenNotice}
        onCancel={() => setOpenNotice(false)}
      >
        <p>确定要发起该通知吗？</p>
      </Modal>

      {/* 询问是否再次发起通知的弹窗 */}
      <Modal
        title="提示"
        centered
        open={openInquire}
        onOk={() => {
          setOpenEditTime(true);
        }}
        onCancel={() => setOpenInquire(false)}
      >
        <p>该通知截至时间已过，是否修改截至时间后重新发起通知？</p>
      </Modal>

      {/* 修改时间，再次发起通知的弹窗 */}
      <Modal
        title="提示"
        centered
        open={openEditTime}
        onOk={ensureOpenEditTime}
        onCancel={() => setOpenEditTime(false)}
      >
        <Form
          layout="inline"
          form={editTimeForm}
          style={{ position: "relative", justifyContent: "center" }}
        >
          <Form.Item name="endTime" label="通知截至时间" {...config}>
            <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};
export default NoticePayment;
